$(function(){	

	/*
	 * create the global variable
	 */
	$mainContainer = $(".image-text");	
	$editModal = $('#edit-modal');
	
	/*
	 *  init modal dialog
	 */
	$editModal.modal({
		backdrop: 'static',
		show: false
	});
	
	/*
	 * init the sortable
	 */
	$('#preview-container').sortable({
		scroll: true,
		opacity: 0.6,
		cursor: "move",
		scrollSensitivity: 80,
		placeholder: 'holder',
		connectWith: "#preview-container",
		forcePlaceholderSize: true,
		start: function(e, ui){
			ui.placeholder.height(ui.item.height());
			ui.placeholder.width(ui.item.width());
		}
	});		
	
	/*
	 * init uploader
	 */	
	var $curImageContainer;
	var uploader = new PicUploader({
		size:'290x200',
		success: function(obj) {
			console.log(obj);
			$curImageContainer.css('background-image','url('+obj.data+')');
		}
	});
	
	/*
	 * clean up the modal content
	 */
	var cleanEditModal = function() {
		$editModal.data("trigger", null);
		$editModal.find(".avatar").css("background-image","none");
		$editModal.find(".text").val("");
		$editModal.find(".link").val("");
		$editModal.find("input[name='itemId']").val("");
		$editModal.find("input[name='categoryId']").val("");
	}
	
	/*
	 * init the modal content
	 */	
	var initEditModal = function($trigger) {
		var imageURL = $trigger.css("background-image")||"none";
		var text = $trigger.find(".text").html();
		var link = $trigger.attr("data-link");
		$editModal.data("trigger", $trigger);
		$editModal.find(".avatar").css("background-image",imageURL);
		$editModal.find(".text").val(text);
		$editModal.find(".link").val(link);
	}
	
	/*
	 * bind the event, show the edit modal when edit the existing image-text
	 */
	$mainContainer.on('click','.btn-edit',function(){
		cleanEditModal();
		var $this = $(this);
		var $trigger = $($this.parents(".preview").get(0));
		initEditModal($trigger);
		$editModal.modal('show');
	});
	
	/*
	 * bind the event, show the edit modal when create a new image-text component
	 */
	$mainContainer.on("click",".fa-plus",function(){
		cleanEditModal();
		$editModal.modal('show');
	});
	
	/*
	 * save one image-text component
	 */
	var saveInfo = function($trigger, callBack) {
		var newImageURL = $editModal.find(".avatar").css("background-image")||"none";
		var newText = $editModal.find(".text").val();
		var newLink = $editModal.find(".link").val();
		if(newImageURL === "none") {
			alert("请先上传图片");
			return;
		}
		else {
			var $categoryId = $editModal.data('categoryId');
			var $itemId = $trigger.data('item-id');
			var image = newImageURL.substring(4,newImageURL.length-1);
			if(image.startsWith("\"")&&image.endsWith("\"")){
				image = image.substring(1,image.length-1);
			}
			var data ={
					categoryId:$categoryId,
					linkUrl:newLink,
					image:image,
					content:newText
				};
			var url;
			if($itemId){
				url = '/web/category/editItem';
				data.sort=$trigger.data("sort");
				data.id=$itemId;
			}else{
				url = '/web/category/addItem';
				data.sort= $mainContainer.find('.preview').last().data('sort') +1||1;
			}
			cAjax({
				url: url,
				type:'post',
				data: data,
				success:function(obj){
					callBack();
					greeting({
						msg:"保存成功",
						confirm:function(){
							window.location.reload();
						}
					});
				}
			});
		}
	}
	
	/*
	 * bind the event, save one image-text component
	 */
	$(".btn-save",$editModal).on("click", function(){
		var $trigger = $editModal.data("trigger");
		var isNew = false;
		if($trigger === null) {
			var $template = $("template#tpl-imageText");
			var $templateContent = $($template.html());
			$trigger = $templateContent;
			isNew = true;
		}
		saveInfo($trigger, function(){
			if(isNew === true) {
				$mainContainer.find(".preview-container").append($templateContent[0]);			
			}
		});
	});
	
	/*
	 * bind the event, upload the image
	 */
	$(".avatar",$editModal).on("click", function(){
		$curImageContainer = $(this);		
		uploader.start();	
	});
	
	/*
	 * delete the image-text component
	 */
	$mainContainer.on('click','.btn-del',function(){
		var $this = $(this);
		actionConfirm({	
			msg:"确认要删除该内容吗？",
			confirm:function(){
				var $itemId = $($this.parents(".preview").get(0)).data("item-id");
				cAjax({
					url: '/web/category/deleteItem',
					type:'post',
					data: {
						itemId:$itemId
					},
					success:function(obj){
						$($this.parents(".preview").get(0)).fadeOut();
					}
				});
				$boxContainer.remove();
				}
			}
		);		
	});
	
	/*
	 * bind the event, save all the image text component, this is needed when the order of image-text is changed
	 */
	$("#save-sort-btn").on("click", function(){
		var $items = $mainContainer.find(".preview");
		var itemIds = new Array();
		var sorts = new Array();
		if($items.length==0){
			greeting({msg:"请先添加数据"});
			return false;
		}
		$items.each(function(i){
			itemIds[i] = $(this).data("item-id");
			sorts[i] = i;
		});
		cAjax({
			url: '/web/category/sortItem',
			type:'post',
			data: {'itemIds':itemIds,'sorts':sorts},
			success:function(obj){
				greeting({msg:"保存顺序成功"})
			},
			error: function(obj) {
			}
		});
	});
});
